//
//  CampusPicBroswerViewController.m
//  ShowYork
//
//  Created by hxh on 2021/3/26.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "CampusPicBroswerViewController.h"
#import "CampusPicBroswerCell.h"
@interface CampusPicBroswerViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)UIButton *saveBtn;
@property (nonatomic,strong)CAGradientLayer *gradientLayer;
@property (nonatomic,assign)NSInteger index;
@property (nonatomic,strong)UIView *toolView;
@property (nonatomic,strong)UILabel *titleLb;
@property (nonatomic,strong)UIButton *backBtn;
@property (nonatomic,strong)NSNumber *schId;
@property (nonatomic,strong)NSURLSessionTask *task;
@property (nonatomic,assign)NSInteger total;
@property (nonatomic,assign)BOOL lastPage;
@end

@implementation CampusPicBroswerViewController

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (instancetype)initWithConfigInfo:(NSDictionary *)configInfo{
    if (self = [super init]) {
        
        self.index = [configInfo[@"currentIndex"] intValue];
        
        self.schId = configInfo[@"schId"];
        
        self.total = [configInfo[@"total"] intValue];
        
        self.lastPage = [configInfo[@"lastPage"] boolValue];
        
        [self.dataArray addObjectsFromArray:configInfo[@"listSource"]];
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor blackColor];
    
    self.toolView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.toolView.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:self.toolView];

    
    [self setToolSubViews];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.sectionInset = UIEdgeInsetsZero;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(kScreenW, kScreenH - kNavBarHeight);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, kNavBarHeight, kScreenW, kScreenH - kNavBarHeight) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.alwaysBounceHorizontal = YES;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[CampusPicBroswerCell class] forCellWithReuseIdentifier:@"CampusPicBroswerCell"];
    
    self.gradientLayer = [CAGradientLayer layer];
    self.gradientLayer.frame = CGRectMake(0,kScreenH - (66 + GK_SAVEAREA_BTM), kScreenW, 66 + GK_SAVEAREA_BTM);
    self.gradientLayer.endPoint = CGPointMake(0.5, 0);
    self.gradientLayer.startPoint = CGPointMake(0.5, 1);
    self.gradientLayer.colors = [NSArray arrayWithObjects:
    (id)[RGBA(0, 0, 0, 0.7) CGColor],
    (id)[RGBA(0, 0, 0, 0.0) CGColor],nil];
    [self.view.layer addSublayer:self.gradientLayer];
    
    self.saveBtn = [[UIButton alloc]init];
    [self.saveBtn addTarget:self action:@selector(saveMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.saveBtn setImage:[UIImage imageNamed:@"campus_save_tag"] forState:UIControlStateNormal];
    [self.saveBtn setImage:[UIImage imageNamed:@"campus_save_tag"] forState:UIControlStateHighlighted];
    [self.view addSubview:self.saveBtn];
    
    
    [self.saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-16);
        make.bottom.equalTo(self.view).offset(-(GK_SAVEAREA_BTM + 20));
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
    
    self.isHideNavBar = YES;
    
    [self loadDataSource];
    
    [self.collectionView setContentOffset:CGPointMake(kScreenW * self.index, 0) animated:YES];
    
}



- (void)setToolSubViews{
    self.titleLb = [[UILabel alloc]init];
    self.titleLb.font = [UIFont boldSystemFontOfSize:18];
    self.titleLb.text = [NSString stringWithFormat:@"%d/%ld",self.index+1,(long)self.total];
    self.titleLb.textColor = [UIColor whiteColor];

    self.backBtn = [[UIButton alloc]init];
    [self.backBtn setImage:[UIImage imageNamed:@"common_back_normal_tag"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.toolView addSubview:self.backBtn];
    
    [self.toolView addSubview:self.titleLb];
    
    [self.titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.toolView);
        make.bottom.equalTo(self.toolView).offset(-8);
    }];
        
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.toolView).offset(16);
        make.bottom.equalTo(self.toolView).offset(-8);
    }];
}

- (void)backMethod{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)saveMethod{
    
    CampusSchoolPictureItemModel *itemModel = self.dataArray[self.index];
    
    if (itemModel.loadImage == nil) {
        return;
    }
    
    UIImage *image = itemModel.loadImage;
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error == nil) {
        [WHToast showMessage:@"成功保存至手机" duration:2 finishHandler:nil];
    }else{
        [WHToast showMessage:@"保存失败" duration:2 finishHandler:nil];
    }
}


- (void)loadDataSource{
    
    if ((self.task != nil && self.task.state == NSURLSessionTaskStateRunning) || self.lastPage) {
        return;
    }
    
    NSInteger page = ceil(self.dataArray.count/10.0f) + 1;
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"pageIndex"] = @(page);
    param[@"pageSize"] = @(10);
    param[@"id"] = self.schId;
    param[@"md5"] = [RPAppManager md5StrWithApi:SchoolPictureList];
    self.task = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(SchoolPictureList) parames:param success:^(id responseObj) {
        
        [self.dataArray addObjectsFromArray:[CampusSchoolPictureItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        
        self.lastPage = [responseObj[RESPONSE][LASTPAGE]boolValue];

        [self.collectionView reloadData];
        
        [self.collectionView setContentOffset:CGPointMake(kScreenW * self.index, 0) animated:YES];
        
        
    } failure:^(id error) {

    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CampusPicBroswerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CampusPicBroswerCell" forIndexPath:indexPath];
    [cell setItemModel:self.dataArray[indexPath.item]];
    return cell;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x/kScreenW;
    if (index != self.index) {
        [UIView performWithoutAnimation:^{
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.index inSection:0];
            [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
        }];
    }
    self.index = index;

}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    NSInteger index = scrollView.contentOffset.x/kScreenW;
    if (scrollView.contentOffset.x <= 0) {
        [WHToast showMessage:@"已是第一张" duration:2 finishHandler:nil];
        return;
    }
    if (index == self.dataArray.count - 1 && self.lastPage) {
        [WHToast showMessage:@"没有更多了" duration:2 finishHandler:nil];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    NSInteger index = scrollView.contentOffset.x/kScreenW;
    
    self.titleLb.text = [NSString stringWithFormat:@"%d/%ld",index+1,(long)self.total];
    if (index == self.dataArray.count - 3 && !self.lastPage) {
        if (self.task != nil && self.task.state == NSURLSessionTaskStateRunning) {
            return;
        }else{
            [self loadDataSource];
        }
    }
    if (index == self.dataArray.count - 1 && !self.lastPage) {
        if (self.task != nil && self.task.state == NSURLSessionTaskStateRunning) {
            return;
        }else{
            [self loadDataSource];
        }
    }
}
@end
